/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.pool2;

import java.util.Objects;

/**
 * {@code PoolableObjectFactory} 的基本实现。这里定义的所有操作本质上都是无操作的。
 *
 * @param <T> Type of element managed in this factory.
 * @see PooledObjectFactory
 * @see BaseKeyedPooledObjectFactory
 * @since 2.0
 */
public abstract class BasePooledObjectFactory<T> extends BaseObject implements PooledObjectFactory<T> {


    /**
     * 创建实例,创建一个可以由池提供服务的实例，并将其封装在由池管理的｛@link PooledObject｝中。
     */
    @Override
    public PooledObject<T> makeObject() throws Exception {
        return wrap(Objects.requireNonNull(create(), () -> String.format("BasePooledObjectFactory(%s).create() = null", getClass().getName())));
    }


    /**
     * 验证实例,确保实例对象是否可用。
     */
    @Override
    public boolean validateObject(final PooledObject<T> p) {
        return true;
    }


    /**
     * 激活实例,重新初始化池返回的实例
     */
    @Override
    public void activateObject(final PooledObject<T> p) throws Exception {
        // The default implementation is a no-op.
    }


    /**
     * 钝化实例,取消初始化要返回到空闲对象池的实例。
     */
    @Override
    public void passivateObject(final PooledObject<T> p) throws Exception {
        // The default implementation is a no-op.
    }


    /**
     * 销毁实例,使用默认 (NORMAL)DestroyMode 销毁池不再需要的实例。
     */
    @Override
    public void destroyObject(final PooledObject<T> p) throws Exception {
        // The default implementation is a no-op.
    }


    /**
     * 创建一个对象实例，该实例将封装在｛@link PooledObject｝中。
     *
     * <p>此方法<strong>必须</strong>支持并发多线程调用</p>
     *
     * @return 要由池提供服务的实例，而不是null。
     * @throws Exception 如果创建新实例时出现问题，则会将其传播到请求对象的代码中。
     */
    public abstract T create() throws Exception;


    /**
     * Wraps the provided instance with an implementation of
     * {@link PooledObject}.
     *
     * @param obj the instance to wrap, should not be null.
     * @return The provided instance, wrapped by a {@link PooledObject}
     */
    public abstract PooledObject<T> wrap(T obj);
}
